package com.tougutips.auth.controller;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.tougutips.auth.service.LoginService;
import com.tougutips.auth.utils.SmsUtils;
import com.tougutips.auth.utils.ValidateCodeUtils;
import com.tougutips.common.redis.service.RedisService;
import com.tougutips.common.user.vo.LoginVO;
import com.tougutips.common.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.TimeUnit;
@Slf4j
@RestController
@RequestMapping("/auth")
public class AuthController {
    @Autowired
    private LoginService loginService;

    @Autowired
    private RedisService redisService;
    /**
     * 发送登录验证码
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public AjaxResult send(@RequestBody LoginVO user){
        String phone = user.getAccount();
        if(StringUtil.isNotEmpty(phone)){
            //生成验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("后端生成的验证码：{}",code);
            //调用腾讯云api
            SmsUtils.send(code,phone,5);
            //设置phone为key，code为value的redis缓存
            redisService.setCacheObject(phone,code,5L,TimeUnit.MINUTES);
            return AjaxResult.success("短信发送成功！");
        }
        return AjaxResult.error("手机号码为空,发送失败！");
    }

    /**
     * 登录和注册接口
     *
     * @param user 登录用户实体
     * @return
     */
    @PostMapping("/login")
    public AjaxResult loginAndRegister(@RequestBody LoginVO user) {
        return loginService.login(user);
    }
}
